import {iMicroConfig, iMicroIFrameFormatData, iMicroMainConfig, iMicroPageMeta, iMicroTokenInfo, isPathMatchMicroConfig} from "@peryl/micro-web";
import {computed, delay, onBeforeUnmount, watch} from "@peryl/react-compose";
import {microApp} from "../microApp";
import {pathJoin} from "@peryl/utils/pathJoin";
import {createEffects} from "@peryl/utils/createEffects";

/**
 * 监听当前子应用的激活的页面
 * 当激活页面变化时，通知子应用跳转路由
 * 当子应用路由变化时，保留当时的子应用，重新激活这个页面时先检查是否有缓存的路由，有缓存的路由就跳转缓存的路由，否则跳转页面配置对象中的路由
 * @author  韦胜健
 * @date    2024.3.24 9:29
 */
export function useCurrentPage(
  {
    microConfig,
    getMainConfig,
    tokenInfo,
    getPublicPath,
    handleNewPage,
  }: {
    microConfig: iMicroConfig,
    getMainConfig?: () => Promise<iMicroMainConfig>,
    tokenInfo: iMicroTokenInfo,
    getPublicPath: () => Promise<{
      publicPathOfSub: string,                        // 子应用的publicPath
      publicPathOfSubWithBaseRoutePath: string,       // 启动应用的publicPath，整体应该是“启动应用的publicPath”+“baseRoute”+“子应用id”+“子应用publicPath”
    }>,
    handleNewPage: (data: iMicroIFrameFormatData & { page: iMicroPageMeta }) => Promise<void>,
  }
) {

  const { effects } = createEffects();

  /**
   * 当前子应用的激活的页面
   * @author  韦胜健
   * @date    2024.3.24 9:26
   */
  const currentPageMeta = computed((): iMicroPageMeta | undefined =>
    microApp.state.tabs
      .map(i => i.pages)
      .flat()
      .find(pageMeta => !!pageMeta.show && isPathMatchMicroConfig(pageMeta.path, microConfig))
  );

  effects.push(() => currentPageMeta.effect.stop());

  effects.push(
    watch(() => currentPageMeta.value, async (newPageMeta) => {
      if (!newPageMeta) {return;}
      console.log(microConfig.id, ' -> handle new page', newPageMeta);
      let result: iMicroIFrameFormatData = {
        purePagePath: '',
        subFullPagePath: '',
        baseFullPagePath: '',
        tokenInfo,
      };

      const { publicPathOfSub, publicPathOfSubWithBaseRoutePath } = await getPublicPath();
      const currentPageCacheFullPath = pageId2fullPathMap[newPageMeta.id];
      const { path } = newPageMeta;

      const subPurePagePath = pathJoin(pathJoin('/' + path).replace(microConfig.id, ''));
      const subFullPagePath = pathJoin(publicPathOfSub, subPurePagePath);
      const baseFullPagePath = pathJoin(publicPathOfSubWithBaseRoutePath, subPurePagePath);
      // console.log(222);
      if (!currentPageCacheFullPath) {
        result.purePagePath = subPurePagePath;
        result.subFullPagePath = subFullPagePath;
        result.baseFullPagePath = baseFullPagePath;
      } else {
        let subPurePagePath = pathJoin('/' +
          pathJoin('/' + currentPageCacheFullPath + '/').replace(pathJoin('/' + publicPathOfSubWithBaseRoutePath + '/'), '')
        );
        if (subPurePagePath.charAt(subPurePagePath.length - 1) === '/') {
          subPurePagePath = subPurePagePath.slice(0, -1);
        }
        const subFullPagePath = pathJoin(publicPathOfSub, subPurePagePath);
        const baseFullPagePath = currentPageCacheFullPath;
        result.purePagePath = subPurePagePath;
        result.subFullPagePath = subFullPagePath;
        result.baseFullPagePath = baseFullPagePath;
      }
      // console.log(333);
      if (microConfig.iframe != null && typeof microConfig.iframe !== "boolean" && !!microConfig.iframe.formatPath) {
        result = await microConfig.iframe.formatPath(result);
      }
      // console.log(444);
      if (!!getMainConfig) {
        const mainConfig = await getMainConfig();
        if (!!mainConfig.formatPath) {
          result = await mainConfig.formatPath(result);
        }
      }
      // console.log(555);
      await handleNewPage({ ...result, page: newPageMeta });
      /*等第一个页面的处理动作（路由）弄完之后，通知FrameModeFrame以及FrameModeNone执行初始化逻辑*/
      /*promise.resolve只有第一次执行的时候有效*/
      microApp.defer.loadMicroReadyMap[microConfig.id].resolve();
    }, { immediate: true })
  );

  /**
   * 缓存某个页面展示过程中，切换的最后一个path，当恢复显示这个页面时，将location.href恢复为这个页面当时最后一个显示的path
   * @author  韦胜健
   * @date    2024.2.22 23:53
   */
  let pageId2fullPathMap = {} as Record<string, string | undefined>;
  effects.push(
    microApp.route.history.onPathChange(async () => {
      await delay();
      if (!currentPageMeta.value) {return;}
      const { pathname, search, hash } = (new URL(window.location.href));
      handlePathChange(pathname + search + hash);
    })
  );

  onBeforeUnmount(effects.clear);

  const handlePathChange = (path: string) => {
    if (!currentPageMeta.value) {return;}
    pageId2fullPathMap[currentPageMeta.value.id] = path;
  };

  return { handlePathChange };
}
